<template>
  <div class="page-modal">
    <el-dialog
      :title="modelConfig.title ?? '新建用户'"
      v-model="dialogVisible"
      width="30%"
      center
      destroy-on-close
    >
      <YZFrom v-bind="modelConfig" v-model="formData" />
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmClick"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import YZFrom from '@/baseUi/from'
import store from '@/store'
export default defineComponent({
  components: { YZFrom },
  props: {
    modelConfig: {
      type: Object,
      required: true
    },
    defaultInfo: { type: Object, default: () => ({}) },
    otherInfo: { type: Object, default: () => ({}) },
    pageName: { type: String, required: true }
  },
  setup(props) {
    const formItems = props.modelConfig.formItems ?? []

    const formOriginData: any = {}

    for (const item of formItems) {
      formOriginData[item.field] = ''
    }

    const dialogVisible = ref(false)

    const formData = ref(formOriginData)

    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modelConfig.formItems) {
          formData.value[item.field] = newValue[item.field]
        }
      },
      { deep: true }
    )
    // 点击确定按钮的逻辑
    const handleConfirmClick = () => {
      dialogVisible.value = false
      if (Object.keys(props.defaultInfo).length) {
        store.dispatch('system/editPageDataAction', {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
        // 编辑
      } else {
        // 新建
        store.dispatch('system/createPageDataAction', {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo }
        })
      }
    }
    return { dialogVisible, formData, handleConfirmClick }
  }
})
</script>

<style lang="scss" scoped></style>
